﻿
var H8TableArray=new Array();



function H8IsDate(dateStr) {
    if (dateStr.indexOf(":") > -1) {
        var r = dateStr.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
        if (r == null) return false; var d = new Date(r[1], r[3] - 1, r[4], r[5], r[6], r[7]);
        return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4] && d.getHours() == r[5] && d.getMinutes() == r[6] && d.getSeconds() == r[7]);
    }
    else if(dateStr.length<10) {
        var r = dateStr.match(/(\d{1,4})(-|\/)(\d{1,2})/);
        if (r == null) return false; var d = new Date(r[1], r[3] - 1, 1);
        return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3]);
    }
    else {
        var r = dateStr.match(/(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})/);
        if (r == null) return false; var d = new Date(r[1], r[3] - 1, r[4]);
        return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]);
    }
}

function H8ConvertToDate(str) {
    var arr = str.split(" ");
    if (str.indexOf("/")>-1) {
        var arr1 = arr[0].split("/");
    }
    else {
        var arr1 = arr[0].split("-");
    }

    if (arr1.length <= 2) {
        arr1[2] = 1;
    }
    if (str.indexOf(":") > -1) {
        var arr2 = arr[1].split(":");

        return new Date(arr1[0], arr1[1], arr1[2], arr2[0], arr2[1], arr2[2]);
    }
    else {
        return new Date(arr1[0], arr1[1], arr1[2]);
    }


}


(function ($){ 
    $.extend($.fn, {
            H8sorterMouse: function () {
               var trs = this;
               this.css("cursor", "pointer");
               return this.hover(function () { $(this).addClass("tr_hoverStyle");}, function (){$(this).removeClass("tr_hoverStyle");}).click(function () {
                 trs.removeClass("tr_hoverStyle").removeClass("bg");
                 $(this).removeClass("tr_hoverStyle").addClass("bg");
               });
            }
     }); // end of extend $.fn

})(jQuery);

    
function TableOrderH8(tableName, tdNum, isAsc, fromnum) {
    arr = new Array();
    var rowscount = $(tableName).find("tbody tr").length; //table中所有行数
    var orderType=$(tableName).find("tr:first th").eq(tdNum).attr("OrderType");
    for (i = 0; i < rowscount - fromnum; i++) {
        var txt = $(tableName).find("tbody tr:eq(" + (i + fromnum) + ") td:eq(" + tdNum + ")").text();
        if (orderType == undefined) {
            if (H8IsDate(txt)) {
                orderType = "dateTime";
            }
            else if (!isNaN(parseFloat(txt))) {
                orderType = "int";
            }
            else {
                orderType = "string";
            }
        }

        switch (orderType) {
            case "int":
                arr[i] = parseFloat(txt);
                break;
            case "date":
            case "dateTime":
                arr[i] = H8ConvertToDate(txt);
                break;
            default:
                arr[i] = txt.py() + escape(txt);
                arr[i] = arr[i].replace(/\'/g, "")
                break;

        }

        $(tableName).find("tbody tr:eq(" + (i + fromnum) + ")").attr('aa', arr[i]);

    }

    var temp = arr[0];
    for (i = 0; i < rowscount - fromnum; i++) {
        for (j = i + 1; j < rowscount - fromnum; j++) {
            if (orderType == "date" || orderType == "dateTime") {
                if (isAsc == "0") {//降序
                    if (arr[i] < arr[j]) {
                        temp = arr[j];
                        arr[j] = arr[i];
                        arr[i] = temp;
                    }
                } else if (isAsc == "1") {//升序
                    if (arr[i] > arr[j]) {
                        temp = arr[j];
                        arr[j] = arr[i];
                        arr[i] = temp;
                    }
                }
            } else if (orderType=="int")
            {
                if (isAsc == "0") {//降序
                    if (arr[i] <arr[j]) {
                        temp = arr[j];
                        arr[j] = arr[i];
                        arr[i] = temp;
                    }
                } else if (isAsc == "1") {//升序
                    if (arr[i] > arr[j]) {
                        temp = arr[j];
                        arr[j] = arr[i];
                        arr[i] = temp;
                    }
                }
            }
            else {
                if (isAsc == "0") {//降序
                    if (arr[i] < arr[j]) {
                        temp = arr[j];
                        arr[j] = arr[i];
                        arr[i] = temp;
                    }
                } else if (isAsc == "1") {//升序
                    if (arr[i] > arr[j]) {
                        temp = arr[j];
                        arr[j] = arr[i];
                        arr[i] = temp;
                    }
                }
            }
            
        }
    }

    pre = -0;
    for (i = 0; i < rowscount - fromnum; i++) {
        if (arr[i] == pre) continue;
        pre = arr[i];
        $(tableName).find("tbody tr[aa='" + arr[i] + "']").each(function () {

            tr = $(this);
            tr.appendTo($(tableName));
        });
    }
}

(function ($) {
    $.fn.extend({
        H8_Grid: function (oWidth, height) {

                       
            //得到当前控件
            var self = this;

            //当前控件参数
            this.option={divTitle:null,divData:null,oWidth:oWidth,height:height};
           
            //当前控件排序
            this.dataOrder=function(){
                var oSelf = this;
                var thIndex = 0;
                oSelf.find("thead th").each(function () {
                   

                    $(this).attr("thIndex", thIndex).attr("order", 0).css("padding-left","3px");
                    thIndex++;

                    $(this).find("span").remove();
                    if ($(this).attr("orderAction") != "false") {
                        $("<span>&nbsp;&nbsp;</span>").appendTo($(this))
                                      .addClass("SortAsc");
                        $(this).css("cursor", "pointer");
                    }

                });


                oSelf.find("thead th[orderaction!='false']").each(function () {
                         //alert($(oSelf).attr("id")); 

                    $(this).unbind("click");
                    $(this).click(function () {
                        
                        $(this).attr("orderClick", true);
                        var order = parseInt($(this).attr("order"), 10)

                        TableOrderH8(oSelf, parseInt($(this).attr("thIndex"), 10), order, 0);

                        if (order == 0) {
                 
                            $(this).attr("order", 1).find("span").removeClass("SortAsc").addClass("SortDesc");
                        }
                        else {
                            $(this).attr("order", 0).find("span").removeClass("SortDesc").addClass("SortAsc");
                        }

                    });

                });
            }

            //显示数据
            this.showData=function(){
                var oSelf=this;

                oSelf.find("thead").show();
                if(oSelf.parent().parent().find(".index_table").length==0)
                {
                    oSelf.parent().parent().parent().find(".index_table").append(oSelf);
                    oSelf.parent().parent().parent().find(".index_table").find("div").remove();
                }
            
            
                
                var width = this.option.oWidth.width();
           

                var tableWidth = 0;
                  oSelf.find("thead th").each(function () {
                    if ($(this).attr("width") != undefined && $(this).attr("width")!="") {
                        tableWidth += parseInt($(this).attr("width").toLowerCase().replace("px", ""), 10);
                    } else {
                        tableWidth += $(this).width();
                    }                 

                });


                //alert(oSelf.html())
                var trTitleHeight = oSelf.find("thead tr").height();
                trTitleHeight=30;

                if (trTitleHeight == null) {
                    alert("null"+oSelf.attr("trheight"))
                    trTitleHeight = parseInt(oSelf.attr("trheight"), 10);
                }
                else {
                    oSelf.attr("trheight", trTitleHeight);
                }



                if (tableWidth < width) {
                    tableWidth = width;
                }
           
                oSelf.css("width", (tableWidth-18) + "px");
                var divTitle = $("<div/>").insertAfter(oSelf)
                                        .css({ "width": width + "px", "overflow": "hidden", "height": (trTitleHeight-6) + "px" });

                var divData = $("<div/>").insertAfter(divTitle)
                                        .css({ "width": width + "px", "overflow": "scroll", "height": (this.option.height - trTitleHeight+6) + "px", "margin-top": "0px" })
                                        .scroll(function () {
                                            $(divTitle).scrollLeft($(divData).scrollLeft());
                                        });


                self.option.divTitle=$(divTitle);
                self.option.divData=$(divData);
       
                var dataTilte = $('<table class="common_table"></table>').appendTo(divTitle)
                                        .css("width", tableWidth + "px");

                dataTilte.append(oSelf.find("thead").clone(true));

                dataTilte.find("thead tr").append("<th style='width:15px'></th>")
            
                oSelf.find("thead").hide();

              //设置内容TD宽度
                oSelf.find("tbody>tr").each(function(){
                     var i=0;
                     //所有TD
                     var tdDatas=$(this).find("td");
                     //所有标题TH
                     var thTitles=dataTilte.find("thead tr:first th");
                     for(var i=0;i<tdDatas.length;i++)
                     {
                        if(i==tdDatas.length-1)
                         {
                            //最后一行TD宽度
                            $(tdDatas[i]).css("width",thTitles.eq(i).width()+thTitles.eq(i+1).width()-15);
                         }
                         else{
                            //每一行TD宽度
                            $(tdDatas[i]).css("width",thTitles.eq(i).width());
                         }
                     }
                });
                $(divData).append(oSelf);
            }

            this.sorterMouse=function(){
           
              this.find("tbody>tr").H8sorterMouse();
            }

         
           
            //排序
            this.dataOrder();

            //显示数据
            this.showData(); 
            
           

            //鼠标事件
            this.sorterMouse();

            
            //窗体resize
            $(window).resize(function () {
                $.each(H8TableArray,function(i,item){
                if(item.option.oWidth.width()>0)
                {   
                    item.option.divTitle.css("width", item.option.oWidth.width());
                    item.option.divData.css("width", item.option.oWidth.width());
                }
                });
            });

          
             //缓存页面所有H8Grid;
          if(self.data("BindH8_Grid")==undefined)
          {
             H8TableArray[H8TableArray.length]=this;
             self.data("BindH8_Grid",true);
          }
          
             $(window).trigger('resize');
             $(window).resize();
            return this;
        }
    });
})(jQuery);


///分页控件
(function ($) {
    $.fn.extend({
        pager: function (appPath,url,postData,callfn,pageSize,isL,isSelect) {
            //得到当前控件
            var self = this;

            if(self.data("pager_Data_kj"))
            {
              
              //return self;
            }
             //默认参数
            var defaultOption = {
                        appPath:"/",
                        pageIndex:1,
                        pageCount: 1,
                        rowCount:1,
                        pageSize:20,
                        postType:"post",
                        url:url,
                        postData:{},
                        showInput:true,
                        showPageCount:true,
                        showRowCount:true,
                        showPageSize:true,
                        isLoad:true,
                        callback:callfn,
                        isSelect:false
                         };
            self.option=defaultOption;
            self.option.appPath = appPath;
            //当前传有分页条数时,则用默认值 
            if(!isNaN(parseInt(pageSize)))
                self.option.pageSize = pageSize;
            //第一次是否加载(默认加载)
            if(isL==null|| isL==undefined)
                self.option.isLoad=true;
            else
                self.option.isLoad=isL;
            //显示分页是否使用下拉(默认不显示)
            if(isSelect==null|| isSelect==undefined)
                self.option.isSelect=false;
            else
                self.option.isSelect=isSelect;
            //当前页码
            var pIndex=self.option.pageIndex;

            

            function getPostData()
            {
                //得到需要提交的参数
                if($.isFunction(postData))
                {
                    self.option.postData=postData();
                }
                else
                {
                    self.option.postData=postData;
                }
                 return   $.extend(defaultOption.postData,{PageSize: self.option.pageSize, PageIndex:self.option.pageIndex});
            }

           
           //添加首页并添加事件
            var first=$('<span><a style="color:#126996;margin-right:20px">首页</a></span>').appendTo(self)
            .attr("disabled","disabled")
            .css("cursor","pointer")
            .addClass("first")
            .click(function(){
                if($(this).attr("disabled")!=true)
                {
                    self.option.pageIndex=1
                    self.getPegerData();
                }
            });
      
            //添加上一页并添加事件
            var prev = $('<span><a style="color:#126996;margin-right:15px">上一页</a></span>').appendTo(self)
            .attr("disabled","disabled")
            .css("cursor","pointer")
            .addClass("prev")
            .click(function(){             
                if($(this).attr("disabled")!=true)
                {               
                    self.option.pageIndex=self.option.pageIndex-1;
                    if(self.option.pageIndex<=0)self.option.pageIndex=1;
                    self.getPegerData();
                }
            });

            //添加下一页并添加事件
             var next = $('<span><a style="color:#126996;margin-right:15px">下一页</a></span>').appendTo(self)
            .attr("disabled","disabled")
            .css("cursor","pointer")
            .addClass("next")
            .click(function(){             
                if($(this).attr("disabled")!=true)
                {
//                    if($("table:visible:last tbody tr",self.prev("div"))!=undefined && $("table:visible:last tbody tr",self.prev("div")).length!=self.option.pageSize )
//                        self.option.pageIndex=self.option.pageIndex;
//                    else
                        self.option.pageIndex=self.option.pageIndex+1;
                    if(self.option.pageIndex>self.option.pageCount)self.option.pageIndex=self.option.pageCount;
                    self.getPegerData();
                }
            });
            //添加末页并添加事件
            var last = $('<span><a  style="color:#126996;margin-right:15px">末页</a></span>').appendTo(self)
            .attr("disabled","disabled")
            .css("cursor","pointer")          
            .addClass("last")
            .click(function(){             
                if($(this).attr("disabled")!=true)
                {
                    self.option.pageIndex=self.option.pageCount;                                    
                    self.getPegerData();
                }
            });

            //$("<span/>").appendTo(self).html('<img src="'+self.option.appPath+'/css/css_images/page_fenqu.gif" style="border-width:0px;" />')
            $("<span/>").appendTo(self).html('|&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
           

            //页码
            var ctlPageCount = $('<span>第<input style="width: 24px; height:14px; border:#3188b4 solid 1px;" >/<label>0</label>页</span>').appendTo(self);
            if(!self.option.showPageCount){
                ctlPageCount.hide();
            }

            //增加分页直接输入项
            var ctlInput=ctlPageCount.find("input")
            .width("24px").val(pIndex).addClass("page_inputStyle");

            //输入项跳转按钮
            var ctlbtn=$('<input type="button">').appendTo(self)
             .addClass("btn_skip")
             .click(function(){
                self.option.pageIndex=parseInt(ctlInput.val(),10);
                self.getPegerData();

             });  
             if(!defaultOption.showInput){
                ctlbtn.hide();
                ctlInput.hide();
             }
            $("<span/>").appendTo(self).html('<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; |</span>')
            //$("<span/>").appendTo(self).html('<img src="'+self.option.appPath+'/css/css_images/page_fenqu.gif" style="border-width:0px;" />')

               //每页显示条数
            var ctlPageSize;
            if(!self.option.isSelect)
            {
                ctlPageSize = $('<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 每页<label>0</label>条&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>').appendTo(self).find("label").text(self.option.pageSize);
            }
            else
            {
                //下拉菜单
                ctlPageSize = $('<span>每页<Select></Select>条</span>').appendTo(self);
                if(!self.option.showPageSize){                
                    ctlPageSize.hide();
                }

                var select =ctlPageSize.find("select");
                for(var i=1;i<=5;i++)
                {
                    select.append("<option value="+(i*10)+">"+(i*10)+"</option>");
                }

                select.val(self.option.pageSize).change(function () { 
                    self.option.pageIndex=1;
                    self.option.pageSize=$(this).val();
                    self.getPegerData();

                });
            }

            //总记录数
            var ctlRowCount = $('<span>共<label id="lblRecordCount">0</label>条</span>').appendTo(self);
            if(!self.option.showRowCount)
             {
                ctlRowCount.hide();
            }
                     
            //请求数据,并执行回调方法
           self.getPegerData=function()
            {
              
              $.ajax({ global: true, url: url, data: getPostData(), success: function (data) {
                    if (data.error == true) {
                        ShowWarn(data.message);
                    }
                    else {
                        if(self.option.pageIndex==1)
                        {
                                self.option.rowCount=data.RowCount;
                                self.option.pageCount=Math.ceil(self.option.rowCount/self.option.pageSize);

                                ctlInput.forceNumber({
                                    min: 1,
                                    max:  defaultOption.pageCount, // 2^64 - 1
                                    scale: 0                   // decimal places
                                 })
                                 .enterQueue(function(){
                                    $(this).next("input").click();
                                 });

                        }
                        self.option.rowCount=data.RowCount;
                        ctlInput.val(self.option.pageIndex);
                        ctlPageCount.find("label").text(self.option.pageCount);
                        ctlRowCount.find("label").text(self.option.rowCount);
                        if(self.option.pageIndex==1)
                        {
                            first.attr("disabled","disabled");
                            prev.attr("disabled","disabled")
                        }
                        else{
                             first.removeAttr("disabled");
                             prev.removeAttr("disabled");
                        }

                        if(self.option.pageIndex>=self.option.pageCount)
                        {
                            next.attr("disabled","disabled");
                            last.attr("disabled","disabled")
                        }
                        else{
                             next.removeAttr("disabled");
                             last.removeAttr("disabled");
                        }

                        self.option.callback(data);
                    }
                }, dataType: "json", type: defaultOption.postType, async: true,error:function (XMLHttpRequest, textStatus, errorThrown) {
                        //alert(errorThrown);
                        if(errorThrown==undefined)
                        {
                            ShowWarn("请求目标不存在,请与管理员联系");
                        }
                        else{
                            ShowWarn("请求页面数据时出错");
                        }
                    }
                });
 
            }    
            

            if(self.option.isLoad)    
                self.getPegerData();

            //self.data("pager_Data_kj",true);
            self.data("pager_Data_kj",false);

            return self;
        }
    });
})(jQuery);